
package camera;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Toast;

public class DoShotCameraActivity extends Activity {

	public static Uri mImageCaptureUri;
	public static Uri mImageCropUri;
	private static final int PICK_FROM_CAMERA = 1;
	private static final int CROP_FROM_CAMERA = 2;
	private static final int CROP_FROM_FILE = 4;
	private static final int PICK_FROM_FILE = 3;
	private static int ACTION_KEY = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		doShot();
	}
	
	public String getRealPathFromURI(Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }




	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {

			switch (requestCode) {
			case PICK_FROM_CAMERA:
				Log.e("Camera","CAMERA");
				doCrop(CROP_FROM_CAMERA);
				break;

			case PICK_FROM_FILE:
				mImageCaptureUri = data.getData();
				
				if (mImageCaptureUri != null) {
					doCrop(CROP_FROM_FILE);
				}
				
				break;

			case CROP_FROM_CAMERA:
				/*
				Intent intentCamera = new Intent(getApplicationContext(),
						P05Activity.class);
				intentCamera.putExtra("imagepath", mImageCropUri.getPath());
				startActivity(intentCamera);
				break;
				*/
				Log.e("FILE RESULT CAMERA",mImageCropUri.getPath());
				break;
				
			case CROP_FROM_FILE:
				/*
				Intent intent = new Intent(getApplicationContext(),
						P05Activity.class);
				intent.putExtra("imagepath", mImageCropUri.getPath());
				startActivity(intent);
				break;
				*/
				Log.e("FILE RESULT",mImageCropUri.getPath());
				break;

			}
		} else {
			switch (requestCode) {
			case CROP_FROM_CAMERA:
				if(mImageCaptureUri != null){
					File file = new File(mImageCaptureUri.getPath());
					if(file.exists()){
						file.delete();
						Log.d("Xoa","Xoa file : " + mImageCaptureUri.getPath());
					}
				}
				
				mImageCaptureUri = makeFilename("tmp_avatar_");
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				
				List<ResolveInfo> list = getPackageManager().queryIntentActivities(
						intent, 0);
				
				if(list.size() > 1){
					intent.setComponent(new ComponentName(list.get(0).activityInfo.packageName, list.get(0).activityInfo.name));
				}
				
				intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
						mImageCaptureUri);

				try {
					intent.putExtra("return-data", true);
					startActivityForResult(intent, PICK_FROM_CAMERA);
				} catch (ActivityNotFoundException e) {
					e.printStackTrace();
				}
				break;
			case CROP_FROM_FILE:
				Intent intent2 = new Intent();

				intent2.setType("image/*");
				intent2.setAction(Intent.ACTION_PICK);
				startActivityForResult(Intent.createChooser(intent2, "Complete action using"),PICK_FROM_FILE);
				break;
			
			}
		}
	}
	
	public Uri makeFilename(String prefix){
		String direct = "/faketwitter";
		
		File directory = new File(Environment.getExternalStorageDirectory() + direct);
		if (!directory.exists()) {
	        boolean test = directory.mkdir();
	        if(test){
	        	Log.e("OK","Tao ok");
	        }else{
	        	Log.e("FAILE","TAO FAILE");
	        }
	    }
		File file = new File(directory,prefix + String.valueOf(System.currentTimeMillis()));
		return Uri.fromFile(file);
	}

	private void doCrop(int KEY) {
		Log.d("Cut","Vao do crop image");
		if(KEY == -1){
			KEY = ACTION_KEY;
		}else{
			ACTION_KEY = KEY;
		}

		final ArrayList<P01CropOption> cropOptions = new ArrayList<P01CropOption>();

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setType("image/*");
		/* Xoa file neu no da ton tai */
		if(mImageCropUri != null){
			File file = new File(mImageCropUri.getPath());
			if(file.exists()){
				file.delete();
				Log.d("Xoa","Xoa file : " + mImageCropUri.getPath());
			}
		}
	
		
		List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, 0);

		int size = list.size();

		if (size == 0) {
			Toast.makeText(this, "Can not find image crop app",Toast.LENGTH_SHORT).show();
			return;
		} else {
			
			mImageCropUri = makeFilename("tmp_avatar_cuted_");
			Log.e("FILE",mImageCropUri.getPath());
			intent.setData(mImageCaptureUri);
			intent.putExtra("outputX", 600);
			intent.putExtra("outputY", 600);
			//intent.putExtra("aspectX", 1);
			//intent.putExtra("aspectY", 1);
			intent.putExtra("scale", true);
			intent.putExtra("output", mImageCropUri);
			intent.putExtra("return-data", true);

			if (size == 1) {
				Intent i = new Intent(intent);
				ResolveInfo res = list.get(0);
				Log.d("Cut","Vao ham cat 1");
				i.setComponent(new ComponentName(res.activityInfo.packageName,res.activityInfo.name));

				startActivityForResult(i, KEY);
			} else {
				for (ResolveInfo res : list) {
					final P01CropOption co = new P01CropOption();

					co.title = getPackageManager().getApplicationLabel(
							res.activityInfo.applicationInfo);
					co.icon = getPackageManager().getApplicationIcon(
							res.activityInfo.applicationInfo);
					co.appIntent = new Intent(intent);

					co.appIntent
							.setComponent(new ComponentName(
									res.activityInfo.packageName,
									res.activityInfo.name));

					cropOptions.add(co);
				}

				P01CropOptionAdapter adapter = new P01CropOptionAdapter(
						getApplicationContext(), cropOptions);

				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle("Choose Crop App");
				builder.setAdapter(adapter,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int item) {
								startActivityForResult(
										cropOptions.get(item).appIntent,
										CROP_FROM_CAMERA);
							}
						});

				builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
					@Override
					public void onCancel(DialogInterface dialog) {

						if (mImageCaptureUri != null) {
							getContentResolver().delete(mImageCaptureUri, null,
									null);
							mImageCaptureUri = null;
						}
					}
				});

				AlertDialog alert = builder.create();
				alert.show();
			}
		}
	}

	public void doShot() {
		// TODO Auto-generated method stub
		final String[] items = new String[] { "Take from camera","Chose from file" };
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.select_dialog_item, items);
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setTitle("Select source");
		builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				
				if (item == 0) {
					if(mImageCaptureUri != null){
						File file = new File(mImageCaptureUri.getPath());
						if(file.exists()){
							file.delete();
							Log.d("Xoa","Xoa file : " + mImageCaptureUri.getPath());
						}
					}
					
					mImageCaptureUri = makeFilename("tmp_avatar_");
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					List<ResolveInfo> list = getPackageManager().queryIntentActivities(
							intent, PackageManager.MATCH_DEFAULT_ONLY);
					
					for(ResolveInfo res : list){
						Log.e("Numbers", "Packet: " + res.activityInfo.packageName + "  Name : " + res.activityInfo.name);
					}
					
					if(list.size() > 1){
						intent.setComponent(new ComponentName(list.get(0).activityInfo.packageName, list.get(0).activityInfo.name));
					}
					intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,mImageCaptureUri);

					try {
						intent.putExtra("return-data", true);

						startActivityForResult(intent, PICK_FROM_CAMERA);
					} catch (ActivityNotFoundException e) {
						e.printStackTrace();
					}
				} else { // pick from file
					Intent intent = new Intent();

					intent.setType("image/*");
					intent.setAction(Intent.ACTION_PICK);
					startActivityForResult(intent, PICK_FROM_FILE);
				}
			}
		});

		final AlertDialog dialog = builder.create();

		dialog.show();
	}
}